package com.example.springboot.excel.poi;

import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * <p>
 * </p>
 *
 * @author Zero
 * @since 2019/6/14
 */
public class ExcelTest {

    public static void main(String[] args) {
        createBook();
    }

    private static void createBook() {
        Workbook wb = new HSSFWorkbook();
        Sheet sheet = wb.createSheet("Sheet1");
        // 创建行
        Row row = sheet.createRow(0);
        // 设置行高
        row.setHeightInPoints(10);
        // 创建单元格
        createCell(wb, row, (short)0, "1");
        createCell(wb, row, (short)1, "2");
        createCell(wb, row, (short)2, "3");
        createCell(wb, row, (short)3, "4");
        // 输出到文件
        FileOutputStream fileOut= null;
        try {
            fileOut = new FileOutputStream("/Users/kermit/Desktop/demo.xls");
            wb.write(fileOut);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileOut!=null) {
                try {
                    fileOut.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private static void createCell(Workbook wb, Row row, short column, String value){
        Cell cell= row.createCell(column);

        cell.setCellValue(new HSSFRichTextString(value));

        CellStyle cellStyle = wb.createCellStyle();
        // 水平对齐/垂直对齐
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        cellStyle.setVerticalAlignment(VerticalAlignment.BOTTOM);
        // 边框粗细上右下左
        cellStyle.setBorderTop(BorderStyle.THIN);
        cellStyle.setBorderRight(BorderStyle.THIN);
        cellStyle.setBorderBottom(BorderStyle.THIN);
        cellStyle.setBorderLeft(BorderStyle.THIN);
        // 边框颜色上右下左
        cellStyle.setTopBorderColor(IndexedColors.RED.getIndex());
        cellStyle.setRightBorderColor(IndexedColors.RED.getIndex());
        cellStyle.setBottomBorderColor(IndexedColors.RED.getIndex());
        cellStyle.setLeftBorderColor(IndexedColors.RED.getIndex());
        // 背景色
        /*cellStyle.setFillBackgroundColor(IndexedColors.AQUA.getIndex());
        cellStyle.setFillPattern(FillPatternType.BIG_SPOTS);*/
        // 前景色
        cellStyle.setFillForegroundColor(IndexedColors.RED.getIndex());
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);

        cell.setCellStyle(cellStyle);
    }

}
